﻿using Microsoft.AspNetCore.Mvc;
using PARK.Common.Configuration;
using PARK.Common.Core.Manager;
using PARK.Common.Extension;
using PARK.Common.Helper;
using PARK.Common.Model.NPOI;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumStatis;
using PARK.Consumer.Interfaces.ConsumRecharge;
using PARK.DataEncryption;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.JsonSerialization;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PARK.Consumer
{
    /// <summary>
    /// 充值管理服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "ConsumStatis", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumStatisService : IConsumStatisService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumRechargeEntity> _consumRechargeRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumRechargeService"/>类型的新实例
        /// </summary>
        public ConsumStatisService(
            ISqlSugarRepository<ConsumRechargeEntity> consumRechargeRepository,
            IUserManager userManager)
        {
            _consumRechargeRepository = consumRechargeRepository;
            _db = _consumRechargeRepository.Context;
            _userManager = userManager;
        }

        #region 充值统计
        /// <summary>
        /// 充值统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("RechargeList")]
        public async Task<dynamic> GetRechargeList([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                if (input.departId == userInfo.companyId)
                {
                    input.departId = null;
                }
                var list = _db.Queryable<ConsumRechargeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(d => d.IsPay == 1)
                    .WhereIF(startDate != null, a => a.BillDate >= startDate)
                    .WhereIF(endDate != null, a => a.BillDate <= endDate)
                    .WhereIF(!string.IsNullOrEmpty(input.departId), d => d.DepartId.Contains(input.departId))
                    .WhereIF(!string.IsNullOrEmpty(input.userId), d => d.CreateUser.Equals(input.userId)) //操作员
                    .Select(d => new
                    {
                        BillDate = d.BillDate.Value.ToString("yyyy-MM-dd"),
                        total = 1,
                        amount = d.RechargeAmt * d.IsImpairment,
                        d.Paytype,

                    })
                    .MergeTable()
                    .Select(d => new
                    {
                        total = SqlFunc.AggregateSum(d.total),
                        amount = SqlFunc.AggregateSum(d.amount),
                        d.Paytype,
                        d.BillDate
                    })
                    .GroupBy(d => new
                    {
                        d.Paytype,
                        d.BillDate
                    })
                    .ToList();
                List<string> date = list.AsQueryable().Select(f => f.BillDate).Distinct().ToList();
                List<ConsumStatisRechargeListOutput> result = new List<ConsumStatisRechargeListOutput>();
                date.ForEach(dt =>
                {
                    ConsumStatisRechargeListOutput.Offline offline = new ConsumStatisRechargeListOutput.Offline();
                    ConsumStatisRechargeListOutput.Online online = new ConsumStatisRechargeListOutput.Online();
                    ConsumStatisRechargeListOutput.Subtotal subtotal = new ConsumStatisRechargeListOutput.Subtotal();
                    var _offline = list.Where(d => d.BillDate == dt && d.Paytype == 2).FirstOrDefault();
                    offline.amount = _offline == null ? 0 : _offline.amount;
                    offline.total = _offline == null ? 0 : _offline.total;
                    var _online = list.Where(d => d.BillDate == dt && d.Paytype == 1).FirstOrDefault();
                    online.amount = _online == null ? 0 : _online.amount;
                    online.total = _online == null ? 0 : _online.total;

                    subtotal.total = offline.total + online.total;
                    subtotal.amount = offline.amount + online.amount;
                    result.Add(new ConsumStatisRechargeListOutput
                    {
                        date = dt,
                        offline = offline,
                        online = online,
                        subtotal = subtotal, 
                    }); ;

                });
                return result;
            }
            else
                return null;

        }
        #endregion

        #region 平台管理充值统计
        /// <summary>
        /// 充值统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("AllRechargeList")]
        public async Task<dynamic> GetAllRechargeListt([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();

            List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
            DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
            if (startDate != null)
            {
                startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
            }
            if (endDate != null)
            {
                endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
            }
            var list = _db.Queryable<ConsumRechargeEntity>()
                .Where(d => d.IsPay == 1)
                .WhereIF(startDate != null, a => a.BillDate >= startDate)
                .WhereIF(endDate != null, a => a.BillDate <= endDate)
                 .WhereIF(!string.IsNullOrEmpty(input.id), d => d.CompanyId.Contains(input.id))
                .WhereIF(!string.IsNullOrEmpty(input.departId), d => d.DepartId.Contains(input.departId))
                .WhereIF(!string.IsNullOrEmpty(input.userId), d => d.CreateUser.Equals(input.userId)) //操作员
                .Select(d => new
                {
                    BillDate = d.BillDate.Value.ToString("yyyy-MM-dd"),
                    total = 1,
                    amount = d.RechargeAmt * d.IsImpairment,
                    d.Paytype,

                })
                .MergeTable()
                .Select(d => new
                {
                    total = SqlFunc.AggregateSum(d.total),
                    amount = SqlFunc.AggregateSum(d.amount),
                    d.Paytype,
                    d.BillDate
                })
                .GroupBy(d => new
                {
                    d.Paytype,
                    d.BillDate
                })
                .ToList();
            List<string> date = list.AsQueryable().Select(f => f.BillDate).Distinct().ToList();
            List<ConsumStatisRechargeListOutput> result = new List<ConsumStatisRechargeListOutput>();
            date.ForEach(dt =>
            {
                ConsumStatisRechargeListOutput.Offline offline = new ConsumStatisRechargeListOutput.Offline();
                ConsumStatisRechargeListOutput.Online online = new ConsumStatisRechargeListOutput.Online();
                ConsumStatisRechargeListOutput.Subtotal subtotal = new ConsumStatisRechargeListOutput.Subtotal();
                var _offline = list.Where(d => d.BillDate == dt && d.Paytype == 2).FirstOrDefault();
                offline.amount = _offline == null ? 0 : _offline.amount;
                offline.total = _offline == null ? 0 : _offline.total;
                var _online = list.Where(d => d.BillDate == dt && d.Paytype == 1).FirstOrDefault();
                online.amount = _online == null ? 0 : _online.amount;
                online.total = _online == null ? 0 : _online.total;

                subtotal.total = offline.total + online.total;
                subtotal.amount = offline.amount + online.amount;
                result.Add(new ConsumStatisRechargeListOutput
                {
                    date = dt,
                    offline = offline,
                    online = online,
                    subtotal = subtotal,
                }); ;

            });
            return result;

        }
        #endregion

        #region 商户对账
        /// <summary>
        /// 商户对账
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("VerifyList")]
        public async Task<dynamic> GetVerifyList([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                else
                {
                    startDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-01");
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                else
                {

                    endDate = DateTime.Now;
                }
                var Pars = new List<SugarParameter>(){
                              new SugarParameter("@companyId",userInfo.companyId),
                              new SugarParameter("@begDate",startDate),
                              new SugarParameter("@endDate",endDate),
                              new SugarParameter("@vPrtPerson",userInfo.userName),                              
                              new SugarParameter("@merchantId",!string.IsNullOrEmpty(input.merchantId)?input.merchantId:""),
                              new SugarParameter("@machineId",!string.IsNullOrEmpty(input.machineId)?input.machineId:"")
                            };
                var Repdt = _db.Ado.UseStoredProcedure().GetDataTable("P_Rep_GetVerifyaccountList", Pars);
                var list = TableEntity.TableToEntity<ConsumStatisVerifyListExOutput>(Repdt);

                ConsumStatisVerifyOutput Output = new ConsumStatisVerifyOutput();
                Output.VerifyList = list;

                #region 组装前端
                List<string> merchans = list.AsQueryable().Select(f => f.ShName).Distinct().ToList();
                List<ConsumStatisVerifyListOutput> result = new List<ConsumStatisVerifyListOutput>();
                merchans.ForEach(shName =>
                {
                    var _list = list.Where(d => d.ShName.Equals(shName)).ToList();
                    List<ConsumStatisVerifyListOutput.MachineInfo> machines = new List<ConsumStatisVerifyListOutput.MachineInfo>();
                    _list.ForEach(d =>
                    {
                        ConsumStatisVerifyListOutput.MachineInfo machine = new ConsumStatisVerifyListOutput.MachineInfo();
                        machine.Posno = d.Posno;
                        machine.Posname = d.Posname;
                        machine.Accamt = d.Accamt;
                        machine.Welfamt = d.Welfamt;
                        machines.Add(machine);

                    });
                    ConsumStatisVerifyListOutput output = new ConsumStatisVerifyListOutput();
                    result.Add(new ConsumStatisVerifyListOutput
                    {
                        TjDate = startDate.ToDateTimeString() + " 至 " + endDate.ToDateTimeString(),
                        ShName = shName,
                        PrtPerson = userInfo.userName,
                        MachineAmtList = machines,
                    });
                });
                Output.ElVerifyList = result;
                #endregion

                return Output;
            }
            else
                return null;
        }
        #endregion

        #region 消费统计
        /// <summary>
        /// 消费统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("TxnList")]
        public async Task<dynamic> GetTxnList([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                else
                {
                    startDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-01");
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                else
                {
                    endDate = DateTime.Now;
                }
                var Pars = new List<SugarParameter>(){
                              new SugarParameter("@companyId",userInfo.companyId),
                              new SugarParameter("@begDate",startDate),
                              new SugarParameter("@endDate",endDate),
                              new SugarParameter("@merchantId",!string.IsNullOrEmpty(input.merchantId)?input.merchantId:""),
                              new SugarParameter("@machineId",!string.IsNullOrEmpty(input.machineId)?input.machineId:""),
                              new SugarParameter("@departId",!string.IsNullOrEmpty(input.departId)?input.departId:""),
                              new SugarParameter("@cardTypeId",!string.IsNullOrEmpty(input.cardTypeId)?input.cardTypeId:"")
                            };
                var Repdt = _db.Ado.UseStoredProcedure().GetDataTable("P_Rep_GetTxnList", Pars);
                var  output = TableEntity.TableToEntity<TxnListOutput>(Repdt);
                return output;
            }
            else
                return null;

        }        
        #endregion

        #region 消费统计
        /// <summary>
        /// 消费统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("TxnListex")]
        public async Task<dynamic> GetTxnListex([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
                {
                    input.departId = null;
                }
                var result = _db.Queryable<ConsumBillEntity>()
                    .Where(d => d.TxnResult.Equals("1"))
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                    .WhereIF(startDate != null, a => a.TxnDate >= startDate)
                    .WhereIF(endDate != null, a => a.TxnDate <= endDate)
                    .WhereIF(!string.IsNullOrEmpty(input.merchantId), a => a.MerchantId.Contains(input.merchantId))
                    .WhereIF(!string.IsNullOrEmpty(input.departId), a => a.DepartId.Equals(input.departId))
                    .Select(d => new
                    {
                        date = d.TxnDate.Value.ToString("yyyy-MM-dd"),
                        total = 1,
                        amount = d.TxnTotalAmt
                    })
                    .MergeTable()
                    .Select(d => new
                    {
                        d.date,
                        total = SqlFunc.AggregateSum(d.total),
                        amount = SqlFunc.AggregateSum(d.amount)
                    })
                    .GroupBy(a => new { a.date })
                    .ToList();
                List<ConsumStatisVerifyListtoOutput> result1 = new List<ConsumStatisVerifyListtoOutput>();
                result.ForEach(dt =>
                {
                    result1.Add(new ConsumStatisVerifyListtoOutput
                    {
                        date = dt.date,
                        total = dt.total,
                        amount = dt.amount,
                    });
                });
                return result1;
            }
            else
                return null;
        }
        #endregion

        #region 导出消费统计
        /// <summary>
        /// 导出消费统计
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/Exporttxn")]
        public async Task<dynamic> Exporttxn([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var exportData = new List<ConsumStatisVerifyListtoOutput>();
                var exportDataNew = new List<ConsumStatisVerifyListtoOutput>();
                exportData = await this.GetTxnListex(input);
                foreach (ConsumStatisVerifyListtoOutput item in exportData)
                {
                    exportDataNew.Add(item);
                }
                List<ParamsModel> paramList = "[{\"value\":\"日期\",\"field\":\"date\"},{\"value\":\"笔数\",\"field\":\"total\"},{\"value\":\"金额\",\"field\":\"amount\"},]".ToList<ParamsModel>();
                ExcelConfig excelconfig = new ExcelConfig();
                excelconfig.FileName = userInfo.organizeName + "_" + "消费统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                excelconfig.HeadFont = "微软雅黑";
                excelconfig.HeadPoint = 10;
                excelconfig.IsAllSizeColumn = true;
                excelconfig.ColumnModel = new List<ExcelColumnModel>();
                List<string> selectKeyList = input.selectKey.Split(',').ToList();
                foreach (var item in selectKeyList)
                {
                    var isExist = paramList.Find(p => p.field == item);
                    if (isExist != null)
                    {
                        excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                    }
                }
                var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
                ExcelExportHelper<ConsumStatisVerifyListtoOutput>.Export(exportDataNew, excelconfig, addPath);
                var fileName = _userManager.UserId + "|" + addPath + "|xls";
                var output = new
                {
                    name = excelconfig.FileName,
                    url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") //"wwwroot/Template/TemporaryFile/" + excelconfig.FileName //
                };
                return output;
            }
            else
                return null;
        }
        #endregion

        #region 餐次统计
        /// <summary>
        /// 消费统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("TimeIntervalList")]
        public async Task<dynamic> getTimeIntervalList([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                else
                {
                    startDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-01");
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                else
                {
                    endDate = DateTime.Now;
                }
                var Pars = new List<SugarParameter>(){
                              new SugarParameter("@companyId",userInfo.companyId),
                              new SugarParameter("@begDate",startDate),
                              new SugarParameter("@endDate",endDate),
                              new SugarParameter("@merchantId",!string.IsNullOrEmpty(input.merchantId)?input.merchantId:""),
                              new SugarParameter("@machineId",!string.IsNullOrEmpty(input.machineId)?input.machineId:""),
                              new SugarParameter("@departId",!string.IsNullOrEmpty(input.departId)?input.departId:""),
                              new SugarParameter("@cardTypeId",!string.IsNullOrEmpty(input.cardTypeId)?input.cardTypeId:"")                              
                            };
                var Repdt = _db.Ado.UseStoredProcedure().GetDataTable("P_Rep_GetTimeIntervalList", Pars);
                var output = TableEntity.TableToEntity<TimeIntervalListOutPut>(Repdt);
                return output;
            }
            else
                return null;

        }
        #endregion

        #region 导出餐次统计
        /// <summary>
        /// 导出餐次统计
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/ExporttimeInterva")]
        public async Task<dynamic> ExporttimeInterva([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var exportData = new List<ConsumStatisVerifyListtoOutput>();
                var exportDataNew = new List<ConsumStatisVerifyListtoOutput>();
                exportData = await this.GetTxnListex(input);
                foreach (ConsumStatisVerifyListtoOutput item in exportData)
                {
                    exportDataNew.Add(item);
                }
                List<ParamsModel> paramList = "[{\"value\":\"日期\",\"field\":\"date\"},{\"value\":\"笔数\",\"field\":\"total\"},{\"value\":\"金额\",\"field\":\"amount\"},]".ToList<ParamsModel>();
                ExcelConfig excelconfig = new ExcelConfig();
                excelconfig.FileName = userInfo.organizeName + "_" + "餐次统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                excelconfig.HeadFont = "微软雅黑";
                excelconfig.HeadPoint = 10;
                excelconfig.IsAllSizeColumn = true;
                excelconfig.ColumnModel = new List<ExcelColumnModel>();
                List<string> selectKeyList = input.selectKey.Split(',').ToList();
                foreach (var item in selectKeyList)
                {
                    var isExist = paramList.Find(p => p.field == item);
                    if (isExist != null)
                    {
                        excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                    }
                }
                var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
                ExcelExportHelper<ConsumStatisVerifyListtoOutput>.Export(exportDataNew, excelconfig, addPath);
                var fileName = _userManager.UserId + "|" + addPath + "|xls";
                var output = new
                {
                    name = excelconfig.FileName,
                    url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") //"wwwroot/Template/TemporaryFile/" + excelconfig.FileName //
                };
                return output;
            }
            else
                return null;
        }
        #endregion

        #region 充值统计
        /// <summary>
        /// 充值统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetRechargeRep")]
        public async Task<dynamic> GetRechargeRep([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                else
                {
                    startDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-01");
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                else
                {
                    endDate = DateTime.Now;
                }
                if (input.departId == userInfo.companyId)
                {
                    input.departId = null;
                }
                var Pars = new List<SugarParameter>(){
                              new SugarParameter("@companyId",userInfo.companyId),
                              new SugarParameter("@begDate",startDate),
                              new SugarParameter("@endDate",endDate),                             
                              new SugarParameter("@userId",!string.IsNullOrEmpty(input.userId)?input.userId:"")
                            };
                var Repdt = _db.Ado.UseStoredProcedure().GetDataTable("P_Rep_GetRecharge", Pars);
                var output = TableEntity.TableToEntity<RechargeRepOutPut>(Repdt);
                return output;
            }
            else
                return null;

        }
        #endregion

        #region 导出充值统计
        /// <summary>
        /// 导出充值统计
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<RechargeRepOutPut>();
            var exportDataNew = new List<RechargeRepOutPut>();
            exportData = await this.RechargeListex(input);
            foreach (RechargeRepOutPut item in exportData)
            {
                exportDataNew.Add(item);
            }
            StringBuilder str = new StringBuilder("[{\"value\":\"日期\",\"field\":\"rq\"},");
            str.Append("{\"value\":\"线上充值笔数\",\"field\":\"xsczqty\"},{\"value\":\"线上充值金额\",\"field\":\"xsczamt\"},");
            str.Append("{\"value\":\"线上退款笔数\",\"field\":\"xstkqty\"},{\"value\":\"线上退款金额\",\"field\":\"xsczamt\"},");

            str.Append("{\"value\":\"线下充值笔数\",\"field\":\"xxczqty\"},{\"value\":\"线下充值金额\",\"field\":\"xxczamt\"},");
            str.Append("{\"value\":\"线下退款笔数\",\"field\":\"xxtkqty\"},{\"value\":\"线下退款金额\",\"field\":\"xxtkamt\"},");

            str.Append("{\"value\":\"小计笔数\",\"field\":\"qty\"},{\"value\":\"小计金额\",\"field\":\"amt\"}]");

            List<ParamsModel> paramList = str.ToString().ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "充值统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<RechargeRepOutPut>.Export(exportDataNew, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") //"wwwroot/Template/TemporaryFile/" + excelconfig.FileName //
            };
            return output;
        }
        /// <summary>
        /// 获取导出充值统计数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<dynamic> RechargeListex([FromQuery] ConsumStatisQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                List<string> queryDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startDate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
                DateTime? endDate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
                if (startDate != null)
                {
                    startDate = new DateTime(startDate.ToDate().Year, startDate.ToDate().Month, startDate.ToDate().Day, 0, 0, 0);
                }
                else
                {
                    startDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-01");
                }
                if (endDate != null)
                {
                    endDate = new DateTime(endDate.ToDate().Year, endDate.ToDate().Month, endDate.ToDate().Day, 23, 59, 59);
                }
                else
                {
                    endDate = DateTime.Now;
                }
                if (input.departId == userInfo.companyId)
                {
                    input.departId = null;
                }
                var Pars = new List<SugarParameter>(){
                              new SugarParameter("@companyId",userInfo.companyId),
                              new SugarParameter("@begDate",startDate),
                              new SugarParameter("@endDate",endDate),
                              new SugarParameter("@userId",!string.IsNullOrEmpty(input.userId)?input.userId:"")
                            };
                var Repdt = _db.Ado.UseStoredProcedure().GetDataTable("P_Rep_GetRecharge", Pars);
                var output = TableEntity.TableToEntity<RechargeRepOutPut>(Repdt);
                return output;
            }
            else
                return null;
        }
        #endregion
    }
}
